Online-Academy
Look, Read, Understand, Apply

throw and throws

Exception: throw and throws

In Java, Exception, throw, and throws are related, but they mean different things.

Exception: An Exception is an abnormal situation/error that occurs while a program is runnign. Example

int a = 10 ;
int b = 0;
int c = a / b; arithmeticException

Java generates an exception because division by zero is not allows. We can handle it using try-catch.

    int age = 15;
    if (age < 24){
        throw new ArithmeticException("Not eligible to choose person");
    }
    
    Here, throw = I am throwing an exception right here.
    Syntax: throw new ExceptionType("message");
    Example: throw new IOException("File Not found");

throws is used in a method declaration to tell the caller that the method may throw an exception.

void readFile() throws IOException{
    //code that may cause IOException
}
Think: throws: This method might throw this exception; 
    whoever calls me should handle it.

For example:
void readFile() throws IOException{
    FileReader f = new FileReader("abx.txt");
}
Then the caller can handle it:
try{
    readFile();
}catch(IOException e){
    System.out.println("File error!");
}

throw vs throws

throwthrows
Used to actually throw an exception Used to declare possible exceptions
Used inside method/block Used in method declaration
Throws one exception at a time Can declare multiple exceptions
Followed by an exception object Followed by exception class names
void test() throws IOException{
    if(soemthingWrong){
        throw new IOException("Something went wrong!");
    }
}

Easy way to memeber

  1. throw -> THROW the exception
  2. throws -> TELL that the method THROWS an exception

* Remember that throw and throws are keywords, while Exception is a class hierarchy (Throwable -> Exception ->...) rather than a keyword.